package com.learn.english.model.param;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.FluxSink;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author TISNIW
 * @version 1.0
 * @date 2025/6/14 20:45
 * @desc
 */
@Getter
@Setter
@Builder
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
@Configuration
public class Emitters {

    private static final Map<String, FluxSink<String>> sessionEmitters = new ConcurrentHashMap<>();

    /**
     * 添加 emitter 到 map
     */
    public static void addEmitter(String sessionId, FluxSink<String> emitter) {
        sessionEmitters.put(sessionId, emitter);
    }

    /**
     * 移除 emitter
     */
    public static void removeEmitter(String sessionId) {
        sessionEmitters.remove(sessionId);
    }

    /**
     * 判断是否存在该会话的 emitter
     */
    public static boolean containsSession(String sessionId) {
        return sessionEmitters.containsKey(sessionId);
    }

    /**
     * 向指定会话发送消息
     */
    public static void sendMessage(String sessionId, String message) {
        FluxSink<String> emitter = sessionEmitters.get(sessionId);
        if (emitter != null) {
            emitter.next(message);
        }
    }
}